<?php
// +----------------------------------------------------------------------
// | Copyright (c) 2019~2022 https://www.meoyun.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed 这不是一个自由软件，不允许对程序代码以任何形式任何目的的再发行
// +----------------------------------------------------------------------
// | Author: 喵云科技 【https://www.meoyun.com】
// +----------------------------------------------------------------------


namespace app\api\controller;

use app\common\model\TopicGroup;
use app\common\service\Message;
use app\common\service\wechat\WeChatMnpService;
use app\common\validate\TopicValidate;
use think\facade\Db;
use think\exception\ValidateException;
use app\common\model\Post as PostModel;
use app\common\model\Topic as TopicModel;
use app\common\model\User as UserModel;

class Topic extends BaseApi
{
    public function list()
    {
        $classId = input("class_id");
        $keyword = input("keyword");

        $where[] = ['status', '=', 2];
        if ($classId) {
            $where[] = ["class_id", "=", $classId];
        }

        if ($keyword) {
            $where[] = ["name", "like", "%" . $keyword . "%"];
        }

        $list = TopicModel::where($where)->paginate(10);

        return $this->data($list->toArray());
    }

    //分类列表
    public function classList()
    {
        $list = Db::name("category")->select()->toArray();
        return $this->data($list);
    }

    //圈子列表，显示最新三条帖子图片
    public function classTopicAreImg()
    {
        $classId = input("class_id");

        $where = [];
        if ($classId > 0) {
            $where[] = ["class_id", "=", $classId];
        }

        $list = Db::name("topic")->where($where)->order("post_num desc")->paginate(10)->each(function ($item) {

            $imgList = [];

            $postList = PostModel::where("type", '=', 1) //只查询图文帖子
            ->where("media", "<>", "[]")
                ->where("topic_id", "=", $item["id"])
                ->order("id desc")
                ->field("media")
                ->limit(3)
                ->select();

            foreach ($postList as $item2) {
                array_push($imgList, $item2["media"][0]);
            }

            $item["img_list"] = $imgList;
            $item["post_num"] = Db::name("post")->where("topic_id", "=", $item["id"])->count();

            return $item;

        })->toArray();

        return $this->data($list);
    }

    //热门圈子
    public function hot()
    {
        $count = input('count', 10);
        $list = TopicModel::withJoin(["userInfo"])->order('post_num desc')->limit($count)->select();
        return $this->data($list);
    }

    public function postClassList()
    {
        $topicId = input("topic_id");
        $list = Db::name("topic_class")->where('topic_id', $topicId)->select()->toArray();
        return $this->data($list);
    }

    //当前登录用户加入的圈子列表
    public function currentUserJoinTopic()
    {
        $userId = $this->getUserId();

        $topicIds = Db::name("user_topic")->where("user_id", $userId)->order('update_time', 'desc')->column("topic_id");

        $list = [];

        foreach ($topicIds as $id) {
            $topic = TopicModel::where("id", $id)->findOrEmpty();

            if (!$topic->isEmpty()) {
                $list[] = $topic;
            }
        }

        return $this->data($list);
    }

    //圈子详情
    public function detail()
    {
        $id = input("id");
        $userId = $this->getUserIdNoAuth();
        $topic = TopicModel::withJoin(["userInfo"])->where('status', 'in', [1, 2])->findOrEmpty($id);

        if ($topic->isEmpty()) {
            return $this->fail('圈子不存在或已关闭', 0);
        }

        $userIds = Db::name("user_topic")->where("topic_id", $id)->column('user_id');

        $adminUid = Db::name("topic_admin")->where("topic_id", $id)->column("user_id");
        $topic["admin_list"] = UserModel::order("update_time desc")->where("id", "in", $adminUid)->limit(9)->select($userIds)->each(function ($item) use ($userId) {
            $where["user_id"] = $userId;
            $where["follow_uid"] = $item["id"];

            $res1 = Db::name("follow")->where($where)->find();

            if ($res1) {
                $item["has_follow"] = 1; //互相关注
            } else {
                $item["has_follow"] = 0; //未关注
            }

            return $item;
        });

        //置顶帖子
        $postIds = Db::name("topic_top")->where("topic_id", $id)->column("post_id");
        $topic["top_post"] = Db::name("post")->where("id", "in", $postIds)->select();

        $topic["is_join"] = false;
        $topic["is_admin"] = false;

        if ($userId) {
            $where[] = ["user_id", "=", $userId];
            $where[] = ["topic_id", "=", $id];


            $res = Db::name("user_topic")->where($where)->find();

            //是否加入圈子
            if ($res) {
                $topic["is_join"] = true;
            }

            //是否圈主或管理员
            if ($topic["user_id"] == $userId) {
                $topic["is_admin"] = true;
            } else {
                $isAdmin = Db::name("topic_admin")->where($where)->find();
                if ($isAdmin) {
                    $topic["is_admin"] = true;
                }
            }
        }

        return $this->data($topic->toArray());
    }

    //查询圈子内用户列表
    public function userList()
    {
        $id = input("id");
        $userId = $this->getUserIdNoAuth();

        $topicUid = Db::name("topic")->where("id", $id)->value("user_id");
        $uids = Db::name("user_topic")->where("topic_id", $id)->column("user_id");
        $list = UserModel::order("update_time desc")->where("id", "<>", $topicUid)->where("id", "in", $uids)->paginate(10)->each(function ($item) use ($id, $userId) {
            $where["user_id"] = $userId;
            $where["follow_uid"] = $item["id"];

            $res1 = Db::name("follow")->where($where)->find();

            if ($res1) {
                $item["has_follow"] = 1; //互相关注
            } else {
                $item["has_follow"] = 0; //未关注
            }

            $isAdmin = Db::name("topic_admin")->where(["topic_id" => $id, "user_id" => $item["id"]])->find();
            if ($isAdmin) {
                $item["is_admin"] = true;
            } else {
                $item["is_admin"] = false;
            }
        });

        return $this->data($list->toArray());
    }

    //当前用户创建的圈子
    public function createTopicList()
    {
        $userId = $this->getUserId();

        $list = Db::name("topic")->where('user_id', $userId)->paginate(10)->toArray();

        return $this->data($list);
    }

    //搜索
    public function search()
    {
        $keyword = input("keyword");
        $where[] = ["name", "like", "%$keyword%"];
        $list = TopicModel::where($where)->paginate(10)->toArray();
        return $this->data($list);
    }

    //创建圈子
    public function topicAdd()
    {
        $userId = $this->getUserId();

        $params = (new TopicValidate())->post()->goCheck();

        $params["user_id"] = $userId;

        //圈子默认公告内容
        $params["notice"] = '圈子规则：
1、不得发布违法、涉黄、辱骂内容
2、禁止发布广告，兼职和实习帖子
3、文明发言，文明上网';

        $topic = TopicModel::create($params);
        $topicId = $topic->id;

        if ($topicId) {
            //写入圈子用户关联表
            Db::name("user_topic")->insert(["user_id" => $userId, "topic_id" => $topicId, "create_time" => time()]);

            //写入默认圈子分类
            $classList = [
                '吐槽',
                '表白',
                '求助',
                '生活'
            ];

            foreach ($classList as $class) {
                Db::name("topic_class")->insert(["topic_id" => $topicId, "name" => $class, "create_time" => time()]);
            }

            return $this->data(['id' => $topicId]);
        }

        return $this->fail();
    }

    public function qrCode()
    {
        try {
            $topicId = input('topic_id');

            if (!is_numeric($topicId)) {
                return $this->fail("非法参数");
            }

            $response = (new WeChatMnpService())->getQrCode('pages/index/index', $topicId);

            $qrcodePath = public_path() . "qrcode/topic";

            if (!file_exists($qrcodePath)) {
                mkdir($qrcodePath);
            }

            $filename = "$qrcodePath/$topicId.png";

            $response->saveAs($filename);

            $data = [
                'url' => request()->domain() . "/qrcode/topic/$topicId.png"
            ];

            return $this->data($data);
        } catch (\Throwable $e) {
            // 失败
            return $this->fail($e->getMessage());
        }
    }

    //加入圈子
    public function joinTopic()
    {
        $userId = $this->getUserId();
        $topicId = input("id");

        $data["user_id"] = $userId;
        $data["topic_id"] = $topicId;
        $data["create_time"] = time();
        $isjoinTopic = Db::name("user_topic")->where($data)->find();

        if ($isjoinTopic) {
            return $this->fail("您已加入圈子");
        }

        $res = Db::name("user_topic")->insert($data);

        if ($res) {
            Db::name("topic")->where("id", $topicId)->inc("user_num")->update();
            return $this->success("加入成功");
        }
        return $this->fail("未知错误");

    }

    //保存圈子板块分类
    public function saveClass()
    {
        $classList = input("class_list/a");

        foreach ($classList as $item) {
            if (isset($item["id"])) {
                Db::name("topic_class")->update($item);
            } else {
                Db::name('topic_class')->insert($item);
            }
        }

        return $this->success("保存成功");
    }

    //删除圈子板块分类
    public function classDel()
    {
        $classId = input("id");

        $res = Db::name("topic_class")->where("id", $classId)->delete();

        if ($res) {
            return $this->success("删除成功");
        }

        return $this->fail('删除失败');
    }

    //编辑圈子信息
    public function setInfo()
    {
        $params = input('post.');

        try {
            $topic = TopicModel::update([
                    'id' => $params["topic_id"],
                    $params['field'] => $params['value']]
            );

            return $this->data($topic->toArray());
        } catch (\Exception $e) {
            return $this->fail($e->getMessage());
        }
    }

    //退出圈子
    public function userQuit()
    {

        $topicId = input("id");
        $userId = $this->getUserId();

        $where[] = ["user_id", "=", $userId];
        $where[] = ["topic_id", "=", $topicId];

        $topicAdminUid = TopicModel::find($topicId)["user_id"];

        if ($topicAdminUid == $userId) {
            return $this->fail("圈主不可退出圈子");
        }

        $res = Db::name("user_topic")->where($where)->delete();

        if ($res) {
            Db::name("topic")->where("id", $topicId)->dec("user_num")->update();
            return $this->success("已退出该圈子");
        }

        return $this->fail();
    }

    /**
     * 圈子编辑资料
     */
    public function saveInfo()
    {
        $params = input("post.");

        $topic = TopicModel::where("id", $params["id"])->findOrEmpty();

        if ($topic->isEmpty()) {
            return $this->fail("圈子信息错误");
        }

        $topic->name = $params['name'];
        $topic->description = $params['description'];
        $topic->cover_image = $params['cover_image'];
        $topic->bg_image = $params['bg_image'];

        $topic->save();

        return $this->success();
    }

    public function updateOpenTime()
    {
        $userId = $this->getUserId();
        $topic_id = input("topic_id");

        Db::name("user_topic")->where(["user_id" => $userId, "topic_id" => $topic_id])->update([
            "update_time" => time()
        ]);

        return $this->success();
    }
}